<template>
    <div class="device-list">
        <ul class="global-operation-list" style="margin-top: 20px;">
            <li class="global-operation-left">
                <ul class="global-filter-list">
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">关键字：</h2>
                        <el-input v-model="searchForm.keyword" @change="getPost" placeholder="媒体名称"
                            clearable></el-input>
                    </li>

                    <li class="global-filter-item">
                        <el-button type="primary" class="global-filter-item-search"
                            :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                            @click="rePosts()">搜索</el-button>
                    </li>
                    <li class="global-filter-item">
                        <el-button type="primary" class="global-filter-item-search" v-if="operationList.includes('add')"
                            @click="showSubmitDialog">导入</el-button>
                    </li>
                    <li class="global-filter-item">
                        <el-button type="primary" class="global-filter-item-search" v-if="operationList.includes('del')"
                            @click="showBatchDel">批量删除</el-button>
                    </li>
                </ul>
            </li>
        </ul>
        <div class="global-table-content">
            <div class="global-table">
                <el-table :data="dataList" :header-cell-style="{
                            background: '#F6F7FA',
                            color: '#333',
                            height: '60px',
                        }" v-loading="tableLoading" :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }"
                    max-height="700" border v-if="dataList && dataList.length > 0">
                    <el-table-column label="媒体名称" prop="title" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="媒体类型" prop="mediaTypeContent" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column label="具体位置" prop="address" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="200px">
                        <template slot-scope="scope">
                            <div style="display: flex;">
                                <div>
                                    <el-button style="font-size: 14px;" type="text"
                                        @click="viewMsg(scope.row)">查看</el-button>
                                </div>
                                <div v-if="operationList.includes('update')" style="padding-left: 10px;">
                                    <el-button style="font-size: 14px;" type="text"
                                        @click="editMsg(scope.row)">编辑</el-button>
                                </div>
                                <div v-if="operationList.includes('del')" style="padding-left: 10px;">
                                    <el-popconfirm title="确定删除该值吗？" @confirm="handleCommand(2, scope.row)">
                                        <el-button slot="reference" style="font-size: 14px;" type="text">删除</el-button>
                                    </el-popconfirm>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="no-data" v-else
                    style="height: calc(100vh - 130px - 80px);display: flex;align-items: center;justify-content: center;flex-direction: column">
                    <img style="width: 265px;height: 120px;margin-bottom: 32px" src="@/assets/images/tyNoData.png"
                        alt="" />
                    <div style="font-size: 16px;color: #A5A9B5">暂无数据~</div>
                </div>
            </div>
            <div class="global-page">
                <div class="global-page-left">
                </div>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :page-sizes="pageSizes" :page-size="pageSize" :current-page="pageNum" background
                    layout="sizes, total, prev, pager, next" :total="total"></el-pagination>
            </div>
        </div>

        <!-- 详情 -->
        <el-dialog title="详情" :visible.sync="showMsgDialogVisible" width="50%" :before-close="beforeShowMsgHandleClose">
            <div>
                <div>
                    <el-descriptions title="详情" :column="1" border>
                        <el-descriptions-item v-for="(item, index) in dataTableKeys" :key="index"
                            :label="dataTable[item]">
                            <div v-if="dataTypeMap[item] && dataTypeMap[item].includes('pic')">
                                <el-image v-if="showMsg[item]" style="width: 50px; height: 50px;" :src="showMsg[item]"
                                    :preview-src-list="[showMsg[item]]" class="avatar"></el-image>
                            </div>
                            <div v-else>{{ showMsg[item] }}</div>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
            </div>
        </el-dialog>

        <!-- 编辑 -->
        <el-dialog title="编辑" :visible.sync="showEditMsgDialogVisible" width="50%"
            :before-close="beforeShowEditMsgHandleClose">
            <div>
                <div>
                    <el-form ref="showMsg" :model="showMsg" label-width="150px">
                        <el-form-item v-for="(item, index) in dataTableKeys" :key="index" :label="dataTable[item]">
                            <div v-if="dataTypeMap[item] && dataTypeMap[item].includes('pic')">
                                <el-upload class="avatar-uploader" action="/checkorder/manager/pc/user/uploadFile" drag
                                    :show-file-list="false" :data="{ token: $store.state.token }"
                                    :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, item)">
                                    <img v-if="showMsg[item]" :src="showMsg[item]" class="avatar" />
                                    <i v-else class="el-icon-plus avatar-uploader-icon"
                                        style="height: 100px;width: 100px;line-height: 100px !important"></i>
                                    <div slot="tip" class="el-upload__tip" style="color: #919baf">
                                        只能上传jpg/png文件
                                    </div>
                                </el-upload>
                            </div>
                            <div v-else-if="dataTypeMap[item] && dataTypeMap[item].includes('textarea')">
                                <el-input type="textarea" :rows="5" v-model="showMsg[item]"></el-input>
                            </div>
                            <div v-else-if="dataTypeMap[item] && dataTypeMap[item].includes('number')">
                                <el-input type="number" v-model="showMsg[item]"></el-input>
                            </div>
                            <div v-else-if="dataTypeMap[item] && dataTypeMap[item].includes('select')">
                                <el-select v-model="showMsg[item]" placeholder="请选择">
                                    <el-option v-for="item in mediaTypeList" :key="item.id" :label="item.name"
                                        :value="item.name">
                                    </el-option>
                                </el-select>
                            </div>
                            <div v-else>
                                <el-input v-model="showMsg[item]"></el-input>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="submit_button">
                    <el-button type="primary" @click="submit">提交</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 上传表单 -->
        <el-dialog title="上传" :visible.sync="showSubmitDialogVisible" width="30%"
            :before-close="beforeShowSubmitDialogHandleClose">
            <div>
                <el-upload class="upload-demo" drag :action="url" :on-progress="uploadFileLoading"
                    :data="{ token: $store.state.token }" :headers="{ 'Access-Control-Allow-Origin': '*' }"
                    :show-file-list="false" :http-request="checkedFile">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
            </div>
        </el-dialog>

        <!-- 批量删除媒体 -->
        <el-dialog title="批量删除媒体" :visible.sync="batchDelDialogVisible" width="30%"
            :before-close="showBatchDelHandleClose">
            <div>
                <el-form label-position="right" label-width="80px" :model="batchDelForm">
                    <el-form-item label="媒体类型">
                        <el-select v-model="batchDelForm.mediaType" placeholder="请选择媒体类型">
                            <el-option v-for="(item,index) in mediaTypeList" :key="index" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="渠道名称">
                        <el-input v-model="batchDelForm.channelName"></el-input>
                    </el-form-item>
                </el-form>
                <div class="submit_button">
                    <el-button type="primary" @click="submitBatchDel">提交</el-button>
                </div>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import axios from "axios";
import APIMedia from "@/api/apiMedia";

export default {
    name: "mediaList",
    props: {
        operationList: Array,
    },
    data() {
        return {
            tokenData: {
                token: localStorage.getItem("mujingtoken")
            },
            searchForm: {
                keyword: "",
                otherProjectType: null,
            },
            url: "",
            tableLoading: false,
            dataList: [],
            pageSize: 10,
            pageNum: 1,
            total: 0,
            pageSizes: [10, 20, 50, 100],
            formLabelWidth: '120px',
            showMsgDialogVisible: false,
            showMsg: {},
            userList: [],
            showSubmitDialogVisible: false,
            uploadLoading: false,
            dataTable: {},
            dataTableKeys: [],
            showEditMsgDialogVisible: false,
            dataTypeMap: {},
            mediaTypeList: [],
            batchDelDialogVisible: false,
            batchDelForm: {
                mediaType: null,
                channelName: '',
            },
        };
    },
    activated() {
        this.url = process.env.VUE_APP_REQUSET_URL + "/checkorder/manager/pc/user/importMediaExcel?token=" + this.$store.state.token;
        this.pageNum = 1;
        this.dataList = [];
        this.getMediaTypeList();
        this.getPost();
    },
    created() { },
    mounted() {
    },
    methods: {
        submitBatchDel(){
            let params = this.batchDelForm
            APIMedia.delBatchMedia(params).then((res) => {
                if (res.key === 1000) {
                    this.$message({
                        message: '提交成功,已删除' + res.result.data ? res.result.data : 0 + '个',
                        type: 'success'
                    });
                    this.batchDelDialogVisible = false
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        showBatchDelHandleClose(){
            this.batchDelDialogVisible = false
        },
        showBatchDel(){
            this.batchDelForm = {
                mediaType: null,
                channelName: '',
            }
            this.batchDelDialogVisible = true
        },
        submit(){
            let showMsg = this.showMsg;
            let params = {
                id: showMsg.id,
                title: showMsg.title,
                mediaType: showMsg.mediaType,
                address: showMsg.specificLocation,
            }
            console.log(showMsg, params)
            if (showMsg.mediaType){
                let mediaTypeId = null;
                this.mediaTypeList.forEach(item => {
                    if (item && item.name === showMsg.mediaType){
                        mediaTypeId = item.id;
                    }
                })
                params.mediaType = mediaTypeId;
            }
            params.otherMsg = JSON.stringify(showMsg);
            APIMedia.updateMedia(params).then((res) => {
                if (res.key === 1000) {
                    this.$message({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.showEditMsgDialogVisible = false
                    this.getPost();
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        handleAvatarSuccess: function (e, file, fileList, item) {
            if (e.key == 1000) {
                this.showMsg[item] = e.result.data;
                this.$message.success({
                    showClose: true,
                    message: "上传成功",
                    duration: 1500
                });
            }
        },
        beforeShowEditMsgHandleClose() {
            this.showEditMsgDialogVisible = false
        },
        editMsg(row) {
            this.showMsg = JSON.parse(row.otherMsg)
            this.showMsg.id = row.id
            this.showEditMsgDialogVisible = true
        },
        checkedFile(obj) {
            let that = this;
            let url = this.url;
            const formData = new FormData();
            formData.append("file", obj.file); //file 和 后端字段要保持一致
            formData.append("token", this.$store.state.token);
            const config = {
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    token: this.$store.state.token,
                },
                timeout: 1000 * 60 * 10, //这里2分钟内的配置是生效的，超过了就不行。。
            };
            const loading = this.$loading({
                lock: true,
                text:
                    "导入中，若数据量过大，则时间较长，在此期间请勿操作，请等待......",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
            return axios
                .post(url, formData, config)
                .then((rs) => {
                    if (rs.status === 200) {
                        let data = rs.data;
                        if (data.key === 1000) {
                            that.$message.success({
                                showClose: true,
                                message: "上传成功",
                                duration: 1500,
                            });
                        } else {
                            that.$message({
                                type: "warning",
                                message: rs.data.message,
                            });
                        }
                    } else {
                        that.$message({
                            type: "warning",
                            message: rs,
                        });
                    }
                    loading.close();
                    that.showSubmitDialogVisible = false
                    that.rePosts()
                })
                .catch((rs) => {
                    loading.close();
                    this.$message({
                        type: "error",
                        message: rs,
                    });
                });
        },
        uploadFileLoading(e) {
            this.uploadLoading = true;
        },
        showSubmitDialog(){
            this.showSubmitDialogVisible = true
        },
        beforeShowSubmitDialogHandleClose(){
            this.showSubmitDialogVisible = false
        },
        viewMsg(row) {
            this.showMsg = JSON.parse(row.otherMsg)
            this.showMsg.id = null
            this.showMsgDialogVisible = true
        },
        beforeShowMsgHandleClose() {
            this.showMsgDialogVisible = false
        },
        handleCommand(type, row) {
            if (type == 1) {
            } else if (type == 2) {
                let params = {
                    id: row.id
                }
                APIMedia.delMedia(params).then((res) => {
                    if (res.key === 1000) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.rePosts();
                    }
                    this.$bus.$emit("show-loading", false);
                });
            }
        },
        formatterTime(time) {
            if (time) {
                return this.$moment(new Date(time)).format("YYYY-MM-DD HH:mm:ss");
            } else {
                return "-";
            }
        },
        // 分页pageSize改变
        handleSizeChange(e) {
            this.pageSize = e;
            this.rePosts();
        },
        // 分页pageNum改变
        handleCurrentChange(e) {
            this.pageNum = e;
            this.getPost();
        },
        // 重新请求
        rePosts() {
            this.pageNum = 1;
            this.dataList = [];
            this.getPost();
        },
        getPost() {
            this.$bus.$emit("show-loading", true);
            const params = {
                token: this.$store.state.token,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            };
            if (this.searchForm.keyword) {
                params.keyword = this.searchForm.keyword;
            }
            APIMedia.getMediaList(params).then((res) => {
                if (res.key === 1000) {
                    let dataTable = res.result.data
                    // 将对象转换为数组
                    let positionMap = Object.entries(dataTable.positionMap);
                    // 根据值进行排序
                    positionMap.sort((a, b) => a[1] - b[1]);
                    // 如果需要将排序后的结果转换回对象
                    let sortedObj = Object.fromEntries(positionMap);
                    console.log(sortedObj);
                    let dataTableKeys = Object.keys(sortedObj)
                    this.dataTableKeys = dataTableKeys
                    this.dataTable = dataTable.classMap
                    this.total = res.result.count;
                    this.dataTypeMap = dataTable.dataType
                    res = res.result.list;
                    res.forEach(item => {
                        if (item.createTime) {
                            item.createDate = this.$moment(item.createTime).format("YYYY-MM-DD HH:mm");
                        }
                    })
                    this.dataList = res;
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        getMediaTypeList() {
            this.$bus.$emit("show-loading", true);
            const params = {
                token: this.$store.state.token,
            };
            APIMedia.getMediaTypeList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result.list;
                    this.mediaTypeList = res;
                }
                this.$bus.$emit("show-loading", false);
            });
        },
    },
};
</script>

<style scoped>
.submit_button{
    display: flex;
    justify-content: center;
}

.mask-img-del-size {
    width: 50px;
    text-align: center;
    height: 50px;
    margin: 25px;
}

.mask-img {
    position: absolute;
    margin-top: -100px;
    width: 100%;
    height: 100%;
    bottom: 0;
    background: rgba(101, 101, 101, 0.6);
    color: #ffffff;
    opacity: 0;
    margin-left: -10px;
}

.banner-pic-sub .mask-img:hover {
    opacity: 1;
    cursor: pointer;
}

.el-upload__tip {
    color: #969799;
    margin-top: 0;
    height: 30px;
    line-height: 30px;
}
.el-upload-dragger{
    width: 100px;
    height: 100px;
}

.avatar-uploader .el-upload .avatar-uploader-icon {
    width: 100px;
    height: 100px;
    line-height: 100px !important;
}
</style>

<style lang="sass">
.avatar-uploader-icon
  font-size: 28px
  color: #8c939d
  width: 178px
  height: 178px
  line-height: 178px !important
  text-align: center
.device-list
  padding-top: 26px
  @include container
.editDialog
  .el-dialog__header
    border-bottom: 1px solid #EFEFEF
    .el-dialog__headerbtn
      font-size: 20px
  .el-dialog__footer
    text-align: left
    margin-left: 120px

</style>
